﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using nelech.Models.DBModel;
using nelech.Controllers.Utils;
using nelech.Views.Shared.Code;
using System.IO;


namespace nelech.Controllers
{
    public class AdvertController : Controller
    {
        nelechDBEntities db = new nelechDBEntities();
        //
        // GET: /Publish/
        [Authorize(Users="admin,editor")]
        public ActionResult CreateAdvert()
        {
            return View();
        }
        //POST
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult CreateAdvert([Bind(Exclude = "id, publish")]Advert advert)
        {
            if (!ModelState.IsValid)
                return View();
            db.AddToAdvert(advert);
            BindAdvertToMultiselectionEntities(advert);
            AddAdvertImages(advert);
            AddTextFile(advert);
            advert.publish = 1;
            db.SaveChanges();

            return RedirectToAction("ListAdvert", "Advert");

        }

        private void AddTextFile(Advert a)
        {
            HttpPostedFileBase pdfFile = Request.Files["pdf"];
            if (pdfFile != null && !string.IsNullOrEmpty(pdfFile.FileName))
            {
                var filename = SharedUtils.GetUniqueFileName(pdfFile.FileName);
                var extension = Path.GetExtension(pdfFile.FileName);
                var url = Path.Combine(@"/Advert/", filename + extension);
                var path = Server.MapPath(url);
                using (var ms = new MemoryStream())
                {
                    pdfFile.InputStream.CopyTo(ms);
                    System.IO.File.WriteAllBytes(path, ms.ToArray());
                }
                a.pdf = url;

            }
            HttpPostedFileBase swfFile = Request.Files["swf"];
            if (swfFile != null && !string.IsNullOrEmpty(swfFile.FileName))
            {
                var filename = SharedUtils.GetUniqueFileName(swfFile.FileName);
                var extension = Path.GetExtension(swfFile.FileName);
                var url = Path.Combine(@"/Advert/", filename + extension);
                var path = Server.MapPath(url);
                using (var ms = new MemoryStream())
                {
                    swfFile.InputStream.CopyTo(ms);
                    System.IO.File.WriteAllBytes(path, ms.ToArray());
                }
                a.swf = url;

            }
        }


        private void AddAdvertImages(Advert p)
        {
            HttpPostedFileBase image = Request.Files["image"];
            if (image != null && !string.IsNullOrEmpty(image.FileName))
            {
                var filename = SharedUtils.GetUniqueFileName(image.FileName);
                var extension = Path.GetExtension(image.FileName);
                var img = new Image
                {
                    path = extension.Equals(".swf", StringComparison.OrdinalIgnoreCase) ?
                    SharedUtils.SaveImage(image.InputStream, "/Advert", filename, extension, Server, 100L, false) :
                    SharedUtils.SaveImage(image.InputStream, "/Advert", filename, extension, Server, 100L, false)
                };
                p.image = img.path;
            }
            HttpPostedFileBase bigImg = Request.Files["bigImg"];
            if (bigImg != null && !string.IsNullOrEmpty(bigImg.FileName))
            {
                var filename = SharedUtils.GetUniqueFileName(bigImg.FileName);
                var extension = Path.GetExtension(bigImg.FileName);
                var img = new Image
                {
                    path = extension.Equals(".swf", StringComparison.OrdinalIgnoreCase) ?
                    SharedUtils.SaveImage(bigImg.InputStream, "/Advert", filename, extension, Server, 100L, false) :
                    SharedUtils.SaveImage(bigImg.InputStream, "/Advert", filename, extension, Server, 100L, false)
                };
                p.bigImg = img.path;
            }

        }
        private void BindAdvertToMultiselectionEntities(Advert advert)
        {
            foreach (var place in db.AdvertPlace)
            {
                var cb = Request.Form["place" + place.id];
                var isChecked = cb.StartsWith("true");
                if (isChecked)
                {
                    advert.AdvertPlace.Add(place);
                }
            }
            foreach (var region in db.Regeon)
            {
                var cb = Request.Form["region" + region.id];
                var isChecked = cb.StartsWith("true");
                if (isChecked)
                {
                    advert.Regeon.Add(region);
                }
            }
        }

        public ActionResult ListAdvert()
        {
            return View(db.Advert.Where(p => p.publish == 1));
        }
        [Authorize(Users="admin,editor")]
        public ActionResult EditAdvert(int id)
        {
            var advert = db.Advert.First(p => p.id == id);
            advert.AdvertPlace.Load();
            advert.Regeon.Load();
            return View("CreateAdvert", advert);
        }
        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult EditAdvert([Bind(Exclude = "image")]Advert advert)
        {
            if (!ModelState.IsValid)
                return View("CreateAdvert");

            // Get the attached entity
            var a = db.Advert.First(r => r.id == advert.id);

            // map in the form is <input type="upload"/> and form["map"].ToString() equals
            // to a .Net class name - thus the old path should be put there unless it's
            // changed by AddTrackImages() below
            advert.image = a.image;
            advert.bigImg = a.bigImg;

            // remove entries from many2many relations (must be removed
            // before renewing them below
            UnbindAdvertFromMultiselectionEntities(a);
            db.SaveChanges();

            // apply changes from the detached object to the attached one
            db.ApplyPropertyChanges(a.EntityKey.EntitySetName, advert);

            AddTextFile(a);

            // add the images
            AddAdvertImages(a);

            // renew entries to many2many relations
            BindAdvertToMultiselectionEntities(a);
            db.SaveChanges();

            return RedirectToAction("ListAdvert");
        }
        private void UnbindAdvertFromMultiselectionEntities(Advert a)
        {
            a.AdvertPlace.Load();
            a.Regeon.Load();
            foreach (var place in a.AdvertPlace.ToArray())
            {
                a.AdvertPlace.Remove(place);
            }
            foreach (var region in a.Regeon.ToArray())
            {
                a.Regeon.Remove(region);
            }
        }
        [Authorize(Users="admin,editor")]
        public ActionResult DeleteAdvert(int id)
        {
            db.DeleteObject(db.Advert.First(p => p.id == id));
            db.SaveChanges();
            return RedirectToAction("RecycleBinAdvert");
        }
        [Authorize(Users="admin,editor")]
        public ActionResult RecycleAdvert(int id)
        {
            var t = db.Advert.First(p => p.id == id);
            t.publish = 0;
            db.SaveChanges();
            return RedirectToAction("ListAdvert");
        }
        [Authorize(Users="admin,editor")]
        public ActionResult RecycleBinAdvert()
        {
            return View(db.Advert.Where(p => p.publish == 0));
        }
        [Authorize(Users="admin,editor")]
        public ActionResult RestoreAdvert(int id)
        {
            var t = db.Advert.First(p => p.id == id);
            t.publish = 1;
            db.SaveChanges();
            return RedirectToAction("RecycleBinAdvert");
        }

        public ActionResult AdvertShow(int id, int? region, int? random1)
        {
            Random random = new Random();

            var adverts = db.Advert.AsEnumerable().Where(p => p.publish == 1 && p.date > DateTime.Now).ToList();
            var adverts1 = new List<Advert>();
            foreach (var a in adverts.OrderBy(p => p.id))
            {
                a.AdvertPlace.Load();
                a.Regeon.Load();
                if (region.HasValue)
                {
                    if (a.AdvertPlace.Any(p => p.id == id) && (a.Regeon.Any(p => p.id == region) || a.Regeon.Any(p => p.id == 21)))
                        adverts1.Add(a);
                }
                else
                {
                    if (a.AdvertPlace.Any(p => p.id == id))
                        adverts1.Add(a);
                }
            }
            List<Advert> advertShow = new List<Advert>();
            if (adverts1.Count() > 0)
            {
                int num1;
                if (random1 == null || !random1.HasValue)
                {
                    num1 = random.Next(0, adverts1.Count() - 1);
                }
                else
                {
                    num1 = random1.Value;
                }
                advertShow.Add(adverts1[num1]);
            }
            ViewData["Id"] = id;
            return PartialView("AdvertShow", advertShow);
        }

        public ActionResult AdvertShowThree(int id, int? region, int? noRundom)
        {
            Random random = new Random();
            var adverts = db.Advert.AsEnumerable().Where(p => p.publish == 1 && p.date > DateTime.Now).ToList();
            var advertsList = new List<Advert>();
            foreach (var a in adverts.OrderBy(p => p.id))
            {
                a.Regeon.Load();
                a.AdvertPlace.Load();
                if (region.HasValue)
                {
                    if (a.AdvertPlace.Any(p => p.id == id) && (a.Regeon.Any(p => p.id == region) || a.Regeon.Any(p => p.id == 21)))
                        advertsList.Add(a);
                }
                else
                {
                    if (a.AdvertPlace.Any(p => p.id == id))
                        advertsList.Add(a);
                }
            }

            List<Advert> advertShow = new List<Advert>();
            if (noRundom != null && noRundom.HasValue)
            {
                advertShow.Remove(advertShow[noRundom.Value]);
            }
            if (advertsList.Count() > 0)
            {
                int num1 = random.Next(0, advertsList.Count() - 1);

                Advert showAdd = advertsList[num1];
                advertShow.Add(showAdd);
                advertsList.Remove(showAdd);
                if (advertsList.Count() - 1 > 0)
                {
                    num1 = random.Next(0, advertsList.Count());
                    showAdd = advertsList[num1];
                    advertShow.Add(showAdd);
                    advertsList.Remove(showAdd);
                }
                if (advertsList.Count() - 1 > 0)
                {
                    num1 = random.Next(0, advertsList.Count());
                    advertShow.Add(advertsList[num1]);
                }
            }
            ViewData["Id"] = id;
            return PartialView("AdvertShow", advertShow);
        }

        public ActionResult RemoveAdvertFile(int id, string fileType)
        {
            var advert = db.Advert.First(p => p.id == id);
            try
            {
                switch (fileType)
                {
                    case "image":
                        try
                        {
                            System.IO.File.Delete(Server.MapPath(advert.image));
                           }
                        catch { }
                            advert.image = "";
                        
                break;
                    case "pdf":
                try
                {
                    System.IO.File.Delete(Server.MapPath(advert.pdf));
                }
                catch
                {
                }
                         advert.pdf = "";
                break;
                    case "bigImg":
                try
                {
                    System.IO.File.Delete(Server.MapPath(advert.bigImg));

                }
                catch { }
                        advert.bigImg = "";
                break;
                  default:
                try
                {
                    System.IO.File.Delete(Server.MapPath(advert.swf));
                }
                catch { }
                advert.swf = "";
                break;

            }
            }
            catch (Exception e)
            {
            }
           
            db.SaveChanges();

            return Redirect(Request.UrlReferrer.ToString());
        }

    }
}
